#!/bin/bash

# check parameters
input_file=${1:?"input file not set"}
output_file=${2:?"output file not set"}

# check input file
if [ ! -e ${input_file} ]
then
	echo "Input file [${input_file}] not found"
	exit 1
fi

#check output file
if [ -e ${output_file} ]
then
	read -s -n1 -p "Output file already exists. Press 'y' to overwrite it or any key to abort." keypress
	echo
	if  [ ${keypress} = 'y' ]
	then
		rm ${output_file}
	else
		echo "Nothing done."
		exit 1
	fi
fi
	
# temp files naming
tmp_path="/tmp/p"
tmp_ext=".swf"
rm ${tmp_path}*${tmp_ext}

# convert pdf to swf
pdf2swf ${input_file} -o "${tmp_path}%${tmp_ext}" -f -T 9

# check number of generated files
nbpages=$(ls -l ${tmp_path}*${tmp_ext} | wc -l)
if (( nbpages <= 0 ))
then
	echo "Detect 0 page converted. Aborting."
	exit 1
fi

# build the combine command
combine_cmd="swfcombine -z -o ${output_file} -T"
for (( num = 1; num <= nbpages; num++ ))
do
	page="${tmp_path}${num}${tmp_ext}"
	if [ ! -e ${page} ]
	then
		echo "Cannot found page file [${page}]"
		exit 1
	fi
  combine_cmd="${combine_cmd} \
  ${num}=${page}"
done

# exec the combine command and exit
echo $combine_cmd
$combine_cmd
echo "Done."
exit 0
